package com.katze.common.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.katze.common.Message;
import com.katze.common.env.AppEnvironment;
import org.apache.poi.ss.usermodel.IndexedColors;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//todo
public class BaseController {

    public BaseController () {}

    /**
     * 初始化应用目录
     * @param name 目录名称，为空时取类名前缀
     */
    protected Path initializeDataDir (String... name) {
        Path resource = name.length == 0?
                AppEnvironment.DATA_DIR.getPath(this.getClass().getSimpleName().replace("Controller", ""))
                :AppEnvironment.DATA_DIR.getPath(name);
        File dir = resource.toFile();
        if (!dir.exists() && !dir.mkdirs()) {
            throw new RuntimeException(dir.getAbsolutePath() + "数据目录无法创建");
        } else {
            return resource;
        }
    }

    /**
     * 表格数据格式
     * @param pageInfo 数据集
     * @return 表格数据
     */
    protected Message toDataTable(Object pageInfo) {
        Map<String, Object> rspData = new HashMap<>();
        if (pageInfo instanceof IPage){
            rspData.put("rows", ((IPage<?>) pageInfo).getRecords());
            rspData.put("total", ((IPage<?>) pageInfo).getTotal());
        } else if (pageInfo instanceof List) {
            rspData.put("rows", pageInfo);
            rspData.put("total", ((List<?>) pageInfo).size());
        } else {
            rspData.put("rows", new ArrayList<>());
            rspData.put("total", 0);
        }
        return Message.ok().data(rspData);
    }


    public void downXlsx(String name, List<?> data, HttpServletResponse response) throws IOException {
        if (data != null && data.size() > 0){
            Class<?> cs = data.get(0).getClass();
            response.setContentType("application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Access-Control-Expose-Headers", "Content-Filename");
            response.setHeader("Content-Filename", URLEncoder.encode(name.concat(".xlsx"), "UTF-8"));

            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            // 背景设置为红色
            headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            headWriteCellStyle.setWriteFont(new WriteFont());
            headWriteCellStyle.getWriteFont().setFontHeightInPoints((short) 12);

            // 内容的策略
            WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
            contentWriteCellStyle.setWriteFont(new WriteFont());

            ExcelWriterBuilder builder = EasyExcel.write(response.getOutputStream(), cs)
                    .registerWriteHandler(new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle))
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy());
            builder.sheet().doWrite(data);
        }
    }
}
